package com.game.center.controller;

import com.game.center.dataconfig.GameGatewayInfo;
import com.game.center.entity.Player;
import com.game.center.entity.User;
import com.game.center.respository.UserRespository;
import com.game.center.service.GameGatewayService;
import com.game.center.service.PlayerService;
import com.game.center.service.UserLoginService;
import com.game.common.error.GameErrorException;
import com.game.common.error.IServerError;
import com.game.common.error.TokenException;
import com.game.common.utils.JWTUtil;
import com.game.common.utils.RSAUtils;
import com.game.netty.error.GameCenterError;
import com.game.netty.http.request.CreatePlayerParam;
import com.game.netty.http.request.LoginParam;
import com.game.netty.http.request.SelectGameGatewayParam;
import com.game.netty.http.response.GameGatewayInfoMsg;
import com.game.netty.http.response.LoginResult;
import com.game.netty.http.response.MessageCode;
import com.game.netty.http.response.ResponseEntity;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author 林道敬
 * @Date 2023-07-29
 * @Description
 **/
@RestController
@RequestMapping("/request")
public class UserController {

    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private UserRespository userRespository;
    @Autowired
    private PlayerService playerService;
    @Autowired
    private GameGatewayService gameGatewayService;

    @PostMapping(MessageCode.USER_LOGIN)
    public ResponseEntity<LoginResult> login(@RequestBody LoginParam loginParam) {

        loginParam.checkParam();//检测请求参数的合法性
        IServerError serverError = userLoginService.verfiySdkToken(loginParam.getOpenid(), loginParam.getToken());
        if (serverError != null) {//请求第三方，验证登陆信息的正确性
            throw GameErrorException.newBuilder(serverError).build();
        }
        User user = userLoginService.login(loginParam);
        LoginResult loginResult = new LoginResult();
        loginResult.setUserId(user.getId());
        System.out.println(user);
        String token = JWTUtil.getUsertoken(user.getOpenid(), user.getId());
        loginResult.setToken(token);// 这里使用JWT生成Token
        return new ResponseEntity<LoginResult>(loginResult);
    }

    @PostMapping(MessageCode.CREATE_PLAYER)
    public ResponseEntity<Player> createPlayer(@RequestBody CreatePlayerParam param, HttpServletRequest request) {
        param.checkParam();
        String token = request.getHeader("token");//从http包头里面获取token的值
        System.out.println("token"+token);
        if (token == null) {
            throw GameErrorException.newBuilder(GameCenterError.TOKEN_FAILED).build();
        }
        JWTUtil.TokenBody tokenBody;
        try {
            tokenBody = JWTUtil.getTokenBody(token);//从加密的token中获取明文信息
        } catch (TokenException e) {
            throw GameErrorException.newBuilder(GameCenterError.TOKEN_FAILED).build();
        }
        System.out.println(tokenBody);
        String openId = tokenBody.getOpenId();
        User user = userLoginService.getUserByOpenId(openId).get();
        String zoneId = param.getZoneId();
        Player player = user.getPlayerMap().get(zoneId);
        if(player == null){
            player = playerService.createPlayer(param.getZoneId(),param.getNickName());
        }
        user.getPlayerMap().put(zoneId,player);
        userRespository.saveOrUpdate(user, user.getId());
        ResponseEntity<Player> response = new ResponseEntity<>(player);
        return response;
    }

    @PostMapping(MessageCode.SELECT_GAME_GATEWAY)
    public Object selectGameGateway(@RequestBody SelectGameGatewayParam param) throws Exception {
        param.checkParam();
        String playerId = param.getPlayerId();
        GameGatewayInfo gameGatewayInfo = gameGatewayService.getGameGatewayInfo(Long.valueOf(playerId));
        GameGatewayInfoMsg gameGatewayInfoMsg = new GameGatewayInfoMsg(gameGatewayInfo.getId(), gameGatewayInfo.getIp(), gameGatewayInfo.getPort());
        Map<String, Object> keyPair = RSAUtils.genKeyPair();// 生成rsa的公钥和私钥
        byte[] publickKeyBytes = RSAUtils.getPublicKey(keyPair);// 获取公钥
        String publickKey = Base64Utils.encodeToString(publickKeyBytes);// 为了方便传输，对bytes数组进行一下base64编码
        String token = playerService.createToken(param, gameGatewayInfo.getIp(), publickKey);// 根据这些参数生成token
        gameGatewayInfoMsg.setToken(token);
        byte[] privateKeyBytes = RSAUtils.getPrivateKey(keyPair);
        String privateKey = Base64Utils.encodeToString(privateKeyBytes);
        gameGatewayInfoMsg.setRsaPrivateKey(privateKey);// 给客户端返回私钥
        ResponseEntity<GameGatewayInfoMsg> responseEntity = new ResponseEntity<>(gameGatewayInfoMsg);
        return responseEntity;
    }


}
